package controllers;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.swing.JOptionPane;

import model.SubscriptionRequestModel;
import model.UserPermissions;
import view.BuyaSubcriptionDetailsGUI;
import client.CliMessage;



         /**
		 * This Class is a BuyaSubscriptionDetailsController which extends AbstractController.
		 *
		 * @author Tal
		 */

		public class BuyaSubscriptionDetailsController extends AbstractController implements IValidateInput
		{	
			       
       			/** The buy sub det view. */
       			private BuyaSubcriptionDetailsGUI buySubDetView;
			       
       			/** The subreq model. */
       			private SubscriptionRequestModel subreqModel;
				 
       			/** The pid. */
			       int pid;
					
					/**
					 * This is Buya Subscription Details Controller constructor.
					 * @param buySubDetView is a Buy a Subcription Details Window GUI instance.
					 * @param subreqModel is a SubscriptionRequest Model instance.
					 */
					public BuyaSubscriptionDetailsController( BuyaSubcriptionDetailsGUI buySubDetView,SubscriptionRequestModel subreqModel) 
					{
						super(buySubDetView,subreqModel);
						this.buySubDetView = buySubDetView;
						this.subreqModel=subreqModel;
						
						buySubDetView.setVisible(true);	
						
						buySubDetView.addBuyActionListener(new BuyListener(this,subreqModel));
					
					}
				
					
					/* (non-Javadoc)
					 * @see controllers.IValidateInput#validateInput()
					 */
					@Override
					public boolean validateInput() 
					{
						
							if(buySubDetView.getCCNumber().equals("") || buySubDetView.getCCV().equals(""))
							{
								
								buySubDetView.displayWrnMessage("You MUST enter All Fields to Buy!!");
								
								return false;
							}
							
							if(!getDateValidation() )
							{
                                    buySubDetView.displayWrnMessage("You Credit Card Date is Expired!!");
								
								return false;
							}
							
							if(buySubDetView.getCreditTypeIndex()<1)
							{
								  buySubDetView.displayWrnMessage("You Have to Choose Credit Card Type!!");
									
									return false;
							}
							
							if(! getTextFieldValidation())	
								return false;
							
							
								
							
							
						return true;
						
					}
					
					/**
					 * checks date validation.
					 *
					 * @return the validate date
					 */
					public boolean getDateValidation()
					{
								
								  //CurrentDate
									Date date = new Date();
									SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
									
									String currTime= sd.format(date);
									System.out.println("curr Date:"+currTime);
								    Date currentDate=null;
									try {
										currentDate = sd.parse(currTime);
									} catch (ParseException e) {
										System.out.println("Current Date Problem Parse");
										e.printStackTrace();
									}
									
                                //Date that from Spinners
									
								    String yourDateString =buySubDetView.getDateFormtDB(); 
								    SimpleDateFormat yourDateFormat = new SimpleDateFormat("yyyy-MM-dd");

								    Date yourDate=null;
									try {
										yourDate = yourDateFormat.parse(yourDateString);
									} catch (ParseException e) {
										 System.out.println("Your Date Problem Parse");
										e.printStackTrace();
									}
                                    
									
									
									//checks validation
								    if (yourDate.after(currentDate) || yourDate.equals(currentDate)) 
								    {
								    	 System.out.println("correct date");
								    	 return true;
								           
								    }else{
								         System.out.println("Before");
								         return false;
								    }
								    
					}
					
					/**
					 * checks text field validation.
					 *
					 * @return the text field
					 */
					public boolean getTextFieldValidation()
					{
						
						String ccv=buySubDetView.getCCV();
						String credit=buySubDetView.getCCNumber();
						
						System.out.println("credit: "+credit.length()+"   ccv:"+ccv.length());
						
						//length checking
						if(ccv.length()>3)
						{
							 buySubDetView.displayWrnMessage("Your CCV number is too Long!!");
							 return false;
						}
						
						if (credit.length()>16)
						{
							 buySubDetView.displayWrnMessage("Your Credit card number is too Long!!");
							 return false;
						}
						
						if(ccv.length()<3)
						{
							 buySubDetView.displayWrnMessage("Your CCV number is too Short!!");
							 return false;
						}
						
						if (credit.length()<16)
						{
							 buySubDetView.displayWrnMessage("Your Credit card number is too Short!!");
							 return false;
						}
						
						
						//check ccv integer
						for(int i=0; i<ccv.length();i++)
						{
							if (ccv.charAt(i)<'0' || ccv.charAt(i)>'9')
							{
								 buySubDetView.displayWrnMessage("Your Must Enter Numbers in ccv!!!");
									return false;
							}
						}
						
						//check credit integer
						for(int i=0; i<credit.length();i++)
						{
							if (credit.charAt(i)<'0' || credit.charAt(i)>'9')
							{
								 buySubDetView.displayWrnMessage("Your Must Enter Numbers in credit card!!!");
									return false;
							}
						}
						
						
						
						return true;
					}
					
					/**
					 * Inner class that handles when Buy Button Pressed , implements ActionListener.
					 *
					 * @author Tal
					 */
					
					class BuyListener implements ActionListener
					{
						
						/** The previus observer. */
						private BuyaSubscriptionDetailsController previusObserver;
						
						/** The subreq model. */
						private SubscriptionRequestModel subreqModel;
						
						/**
						 * Instantiates a new buy listener.
						 *
						 * @param previusObserver the previus observer
						 * @param subreqModel the subreq model
						 */
						public BuyListener(BuyaSubscriptionDetailsController previusObserver,  SubscriptionRequestModel subreqModel)
						{
						
							this.previusObserver=previusObserver;
							this.subreqModel=subreqModel;
						}
						
					
						/* (non-Javadoc)
						 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
						 */
						@Override
						public void actionPerformed(ActionEvent arg0) 
						{
							
							if(!validateInput())
								return;
	                           
							buySubDetView.displayWrnMessage("");
							//init subreqModel
							subreqModel.setCreditN(Long.parseLong(buySubDetView.getCCNumber()));
							subreqModel.setCCV(Integer.parseInt(buySubDetView.getCCV()));
							subreqModel.setExpire(buySubDetView.getDateFormtDB());
							subreqModel.setType(buySubDetView.getCreditType());
							
							UserPermissions up = UserPermissions.getInstance(0, null, null);
							int uid = up.getCurrUserID();
							String creditN = buySubDetView.getCCNumber();
							String ccv = buySubDetView.getCCV();
							String type=buySubDetView.getCreditType();
							
							//validate credit card and ccv from db
							String sql = "search" + "SELECT * " 
						                          + " FROM payment_method AS p , cus_payment_method AS c" 
						                          + " WHERE c.pid = p.pid"
						                          + " AND p.creditnum = '" + creditN + "'" 
							                      +	" AND c.uid = "+ uid
							                      + " AND p.ccv <> '" + ccv + "'" 
							                      + " UNION"
							                      + " SELECT * " 
						                          + " FROM payment_method AS p , cus_payment_method AS c" 
							                      + " WHERE c.pid = p.pid"
							                      + " AND p.creditnum = '" + creditN + "'" 
							                      +	" AND c.uid <> "+uid+" ";
									 
						// Send a query to DB
							sendToServer(sql);
		
						}
					}



					
					/* (non-Javadoc)
					 * @see client.IObserve#handleDBRequestSuccess()
					 */
					@Override
					public void handleDBRequestSuccess()
					{
						
						
					}
				
					
					/* (non-Javadoc)
					 * @see client.IObserve#handleDBSearchResult(client.CliMessage)
					 */
					@Override
					public void handleDBSearchResult(CliMessage dbResult) 
					{	
						
						ArrayList<HashMap<String,String>> res = ((CliMessage)dbResult).getSrs();
						
						if(res.get(0).get("CCV")!=null)
						{
						  // System.out.println("enter ivalid");
							buySubDetView.displayWrnMessage("Invalid credit details. please check your card!");
							buySubDetView.clearFields();
						}
						else
						{
							 System.out.println("enter pid");
							 pid=Integer.parseInt((res.get(0).get("PID")));
							 int uid; 
							 
								//insert unregistered customer to pending subscription
								 uid = subreqModel.getUID();
								int gid = subreqModel.getGID();
								int area=subreqModel.getLocation();
								int status=0;
										
								//insert to subreq
								String insertQuery = "adu"	+"INSERT INTO subreq "
									                    	+"(uid,gid,pid,area,isapprovedbycussrvc) VALUES "
									                    	+"(" + uid + "," + gid + ","+ pid +","+ area +"," + status + ")";
								
								
								sendToServer(insertQuery);
								
								
								 uid = subreqModel.getUID();
								//insert to cus_payment_method
								String insertQuery2 = "adu"	+"INSERT INTO cus_payment_method "
									                    	+"(uid,pid) VALUES "
									                    	+"(" + uid + ","+ pid +")";
								
								
								sendToServer(insertQuery2);
								
								 JOptionPane.showMessageDialog(null, "Thank you for Purchase The "+subreqModel.getServiceByName(gid)+" ! \n"
											+ "We Hope You Will Enjoy Our Services!!!", "Subscription Information", JOptionPane.INFORMATION_MESSAGE);
								
								//return to buy another packege
								buySubDetView.clickBackButton();
								
								//select the rest of subscription
								String searchQuery = "search"	+"SELECT t.serviceid,t.description,t.price "
										                        +" FROM taarif AS t, groups AS g"
				                                                +" WHERE t.serviceid=g.gid AND g.type=1";

							
								
							
								sendToServer(searchQuery);
							 
						}
						
					}
						
					
					/* (non-Javadoc)
					 * @see client.IObserve#handleNullSearchResult()
					 */
					@Override
					public void handleNullSearchResult() 
					{
						//System.out.println("enter null");
						String creditN = buySubDetView.getCCNumber();
						String ccv = buySubDetView.getCCV();
						String Expire=buySubDetView.getDateFormtDB();
						String type=buySubDetView.getCreditType();
					
						
						String insertQuery = "adu"	+"INSERT INTO payment_method "
		                                         	+"(creditnum,ccv,expire,type) VALUES "
		                                          	+"('" + creditN + "','" + ccv + "','" + Expire + "','" + type + "'"+")";
						
						
						
						  sendToServer(insertQuery);
	
	                                            //get the last pid that insert
	                         String searchQuery= "search" +"SELECT p.pid"
			                                              + " FROM payment_method AS p "
			                                              + " ORDER BY p.pid DESC "
	                                                      + " LIMIT 1";
	                          sendToServer(searchQuery);
	
		
					}


}
